﻿using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.IO;
using System.Linq;
using System.Text;
using System.Web;
using System.Xml;
using System.Xml.Serialization;


namespace ListFileMaker
{
    /// <summary>
    /// This class uses XmlSerializer to do both sides of conversion to xml string
    /// </summary>
    /// <typeparam name="T">any Serializable class</typeparam>
    public class Serializer<T>
    {
        /// <summary>
        /// Convert an instance to XML string
        /// </summary>
        /// <param name="item"></param>
        /// <returns></returns>
        [DebuggerStepThrough]
        public string Serialize(T item)
        {

            var ms = new MemoryStream();
            var writer = new XmlTextWriter(ms, Encoding.Unicode);

            var serializer = new XmlSerializer(typeof(T));
            serializer.Serialize(writer, item);

            writer.Flush();
            ms.Position = 0;

            var reader = new StreamReader(ms);
            return reader.ReadToEnd();

        }

        /// <summary>
        /// another version, could be better
        /// </summary>
        /// <param name="item"></param>
        /// <returns></returns>
        private string GetSerialize2(T item)
        {
            var wr = new StringWriter(new StringBuilder());

            var serializer = new XmlSerializer(typeof(T));
            serializer.Serialize(wr, item);

            wr.Close();
            return wr.GetStringBuilder().ToString();
        }

        /// <summary>
        /// Convert the XML string to an instance of an object
        /// </summary>
        /// <param name="xml"></param>
        /// <returns></returns>
        [DebuggerStepThrough]
        public T Deserialize(string xml)
        {
            var stream = new XmlTextReader(new StringReader(xml));
            var serializer = new XmlSerializer(typeof(T));
            return (T)serializer.Deserialize(stream);
        }
    }
}